package com.qiku.controller;

import com.qiku.domain.*;
import com.qiku.service.MenuService;
import com.qiku.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;

    /**
     * 角色列表查询&条件查询
     *
     * @param roleVo
     * @return
     */
    @PostMapping("/findAllRole")
    public ResponseResult findAllRole(@RequestBody RoleVo roleVo) {
        try {
            List<Role> roleList = roleService.findAllRole(roleVo);
            ResponseResult result = new ResponseResult(true, 200, "响应成功~", roleList);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 添加&修改角色
     *
     * @param role
     * @return
     */
    @PostMapping("/saveOrUpdateRole")
    public ResponseResult saveOrUpdateRole(@RequestBody Role role) {
        ResponseResult result = null;
        if (null != role.getId() && 0 < role.getId()) {
            roleService.updateRole(role);
            result = new ResponseResult(true, 200, "修改成功~", null);
        } else {
            roleService.saveRole(role);
            result = new ResponseResult(true, 200, "保存成功~", null);
        }
        return result;
    }

    /**
     * 删除角色
     *
     * @return
     */
    @GetMapping("/deleteRole")
    public ResponseResult deleteRole(Integer id) {
        roleService.deleteRole(id);
        ResponseResult result = new ResponseResult(true, 200, "响应成功~", null);
        return result;
    }

    /**
     * 根据角色ID查询关联菜单ID
     *
     * @param roleId
     * @return
     */
    @GetMapping("/findMenuByRoleId")
    public ResponseResult findMenuByRoleId(@RequestParam Integer roleId) {
        List<Integer> menuId = roleService.findMenuByRoleId(roleId);
        ResponseResult result = new ResponseResult(true, 200, "响应成功~", menuId);
        return result;
    }

    /**
     * 查询所有父子菜单信息
     *
     * @return
     */
    @GetMapping("/findAllMenu")
    public ResponseResult findAllMenu() {
        //-1 表示查询所有菜单数据
        List<Menu> menuList = menuService.findSubMenuListByPid(-1);
        Map<String, Object> map = new HashMap<>();
        map.put("parentMenuList", menuList);
        ResponseResult result = new ResponseResult(true, 200, "响应成功", map);
        return result;
    }

    /**
     * 为角色分配菜单
     * @param roleMenuVo
     * @return
     */
    @PostMapping("/RoleContextMenu")
    public ResponseResult RoleContextMenu(@RequestBody RoleMenuVo roleMenuVo) {
        roleService.RoleContextMenu(roleMenuVo);
        ResponseResult result = new ResponseResult(true, 200, "响应成功", null);
        return result;
    }
}
